package org.common.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Component;

/**
 * redis服务
 */
@Slf4j
@Component
public class RedisService {

    private RedissonClient redissonClient;

    public void initRedisService(String url, String password) {
        Config config = new Config();
        config.useSingleServer()
                .setAddress(url)
                .setPassword(password);
        redissonClient = Redisson.create(config);

        log.info("redis service ok!");
    }

    public void set(String key, Object value) {
        RBucket<Object> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }

    public <T> T get(String key, Class<T> clz) {
        RBucket<T> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    public Long increase(String key) {
        return increase(key, 1L);
    }
    public Long increase(String key, long addValue) {
        RAtomicLong atomicLong = redissonClient.getAtomicLong(key);
        return atomicLong.addAndGet(addValue);
    }

}
